package com.meixun.xuanke.user.controller;


import com.alibaba.fastjson.JSON;
import com.meixun.xuanke.user.model.LoginLog;
import com.meixun.xuanke.user.model.User;
import com.meixun.xuanke.user.service.ActiveMQService;
import com.meixun.xuanke.user.service.UserService;
import com.meixun.xuanke.user.util.IPaddress;
import com.meixun.xuanke.user.util.ParamUtil;
import com.meixun.xuanke.user.util.RequestUtil;
import com.meixun.xuanke.user.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@CrossOrigin
@RestController
@EnableAutoConfiguration
public class UserController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private ActiveMQService activeMQService;

    @RequestMapping("/")
    @ResponseBody
    public String index (HttpServletRequest request){
        return "选课登录微服务系统";
    }

    /**
     * 授权登录
     * @param account
     * @param pass
     * @return
     */
    @ResponseBody
    @RequestMapping("/login")
    public String login (HttpServletRequest request, @RequestParam("account")String account, @RequestParam("pass")String pass, @RequestParam("source")String source){
        User user = userService.login(account,pass);
        if (user!=null){
            user.setPass(null);
            if(user.getOnOff()!=1){
                return ResultUtil.getEmptyjson("登录失败，该账户服务已关闭");
            }
            String token =UUID.randomUUID().toString();
            if (user.getType()==3||user.getType()==4){
                //家长和学生，其他用户的不存
                user.setGrade(userService.getGrade(user.getStuUserId()));



                redisTemplate.opsForValue().set("userJson:" +  token,JSON.toJSON(user).toString(),30, TimeUnit.MINUTES);
                //刷新token
                redisTemplate.opsForValue().set("tokenList:" +  user.getStuUserId(), token, 30, TimeUnit.MINUTES);
                logger.info("账户登录成功 userName："+account);
                source=ParamUtil.isNull(source)?"2":source;
               try {
                   String loginIP = IPaddress.getRemoteAddrIp(request);
                   String ipArr[] = loginIP.split("\\+");
                   String LoginIP = ipArr[0].split(":")[0];//ip
                   String loginPort = ipArr[0].split(":")[1];//端口
                   String proxyIPPort = ipArr[1];//域名
                   LoginLog  loginLog = new LoginLog(user.getUserId(),LoginIP, loginPort,proxyIPPort, source);
                   activeMQService.addLoginLog(loginLog);
               }catch (Exception e){
                   String loginIP = IPaddress.getIpAddr(request);
                   String loginIP2 = IPaddress.getRemoteAddrIp(request);
                   LoginLog  loginLog = new LoginLog(user.getUserId(),loginIP, "80",loginIP2, source);
                   activeMQService.addLoginLog(loginLog);
               }
            }
            return ResultUtil.getTokenJson(user,"账户登录成功",token);
        }
        return ResultUtil.getEmptyjson("登录失败，账号或者密码错误");
    }
    /**
     * 授权登录
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping("/authorityLogin")
    public String userId (HttpServletRequest request, @RequestParam("userId")String userId){
        String token=request.getParameter("token");
        if(!ParamUtil.isNull(token)){
            String userJson = (String) (redisTemplate.opsForValue().get("userJson:" +  token));
            request.setAttribute("userJson",userJson);
            logger.info("userJson:"+userJson);
            User user=RequestUtil.getUser(request);
            if(user!=null){
                return ResultUtil.getTokenJson(user,"账户登录成功",token);
            }
        }

        User user = userService.getUserByUserId(userId);
        if (user!=null){
            user.setPass(null);
            if(user.getOnOff()!=1){
                return ResultUtil.getEmptyjson("登录失败，该账户服务已关闭");
            }
            token =UUID.randomUUID().toString();
            if (user.getType()==3||user.getType()==4){
                //家长和学生，其他用户的不存
                user.setGrade(userService.getGrade(user.getStuUserId()));

                redisTemplate.opsForValue().set("userJson:" +  token,JSON.toJSON(user).toString(),30, TimeUnit.MINUTES);
                //刷新token
                redisTemplate.opsForValue().set("tokenList:" +  user.getStuUserId(), token, 30, TimeUnit.MINUTES);
                logger.info("账户登录成功 userId："+userId);
                String source="4";
                try {
                    String loginIP = IPaddress.getRemoteAddrIp(request);
                    String ipArr[] = loginIP.split("\\+");
                    String LoginIP = ipArr[0].split(":")[0];//ip
                    String loginPort = ipArr[0].split(":")[1];//端口
                    String proxyIPPort = ipArr[1];//域名
                    LoginLog  loginLog = new LoginLog(user.getUserId(),LoginIP, loginPort,proxyIPPort, source);
                    activeMQService.addLoginLog(loginLog);
                }catch (Exception e){
                    String loginIP = IPaddress.getRemoteAddrIp(request);
                    LoginLog  loginLog = new LoginLog(user.getUserId(),loginIP, "80",loginIP, source);
                    activeMQService.addLoginLog(loginLog);
                }
            }
            return ResultUtil.getTokenJson(user,"账户登录成功",token);
        }
        return ResultUtil.getEmptyjson("授权登录失败，用户不存在");
    }


    @ResponseBody
    @GetMapping("/addLoginLog")
    public String addLoginLog (@RequestParam("userId")String userId
            , @RequestParam("loginIP")String loginIP
            , @RequestParam("loginPort")String loginPort
            , @RequestParam("proxyIPPort")String proxyIPPort
            , @RequestParam("loginSource")String loginSource){
        LoginLog  loginLog = new LoginLog(userId,loginIP, loginPort,proxyIPPort, loginSource);
        activeMQService.addLoginLog(loginLog);
        return ResultUtil.getjson("","ok");
    }


    /**
     * 更新缓存
     * @return
     */
    @ResponseBody
    @RequestMapping("/init")
    public String init (){
        userService.init();
        return ResultUtil.getjson("","更新成功");
    }
    /**
     * 更新缓存
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateCacheBySchool")
    public String updateCacheBySchool ( @RequestParam("schoolId")String schoolId){
        userService.initBySchool(schoolId);
        return ResultUtil.getjson("","更新成功");
    }
    /**
     * 更新缓存
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateCacheByUser")
    public String updateCacheByUser (@RequestParam("userId")String userId){
        userService.initByUser(userId);
        return ResultUtil.getjson("","更新成功");
    }
    /**
     * 更新缓存
     * @return
     */
    @ResponseBody
    @RequestMapping("/updateCacheAll")
    public String updateCacheAll (){
        userService.init();
        return ResultUtil.getjson("","更新成功");
    }
}
